package com.efounder.form.action;

import android.content.DialogInterface;
import androidx.appcompat.app.AlertDialog;

import com.efounder.common.TCommonRequestManager;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.form.model.JSONFormModel;
import com.efounder.mobilecomps.R;
import com.efounder.util.AppContext;
import com.efounder.util.DateUtil;
import com.efounder.util.ToastUtil;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.utilcode.util.ActivityUtils;
import com.utilcode.util.QMUIToastUtils;

import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.HashMap;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.utilcode.util.ActivityUtils.getTopActivity;

/**
 * 单据保存
 *
 * @autor yqs
 * @date 2019/4/13 15:51
 **/
public class FormSubmitAction extends ActionComponent {
    private String actionText;
    private String actionIcon;

    private JSONFormModel formModel;

    public JSONFormModel getFormModel() {
        return formModel;
    }

    public void setFormModel(JSONFormModel formModel) {
        this.formModel = formModel;
    }

    @Override
    public void setActionText(String text) {
        actionText = text;
    }

    @Override
    public String getActionText() {
        return actionText;
    }

    @Override
    public void setActionIcon(String icon) {
        actionIcon = icon;
    }

    @Override
    public String getActionIcon() {
        return actionIcon;
    }


    @Override
    public void doAction() {
        String GUID = (String) formModel.getDataContainer().getValue("GUID", "");
        String MDL_ID = (String) formModel.getDataContainer().getValue("MDL_ID", "");
        String FLOW_ID = (String) formModel.getDataContainer().getValue("FLOW_ID", "");
        String NODE_ID = (String) formModel.getDataContainer().getValue("NODE_ID", "");
        String Product = (String) formModel.getDataContainer().getValue("Product", "");

        String opinion = "提交(来自Android手机APP)";
        String opLevel = "00";

        JSONObject envRoot = new JSONObject();
        JSONObject paramRoot = new JSONObject();
        JSONObject param = new JSONObject();
        //点击保存按钮之后服务器返回的数据
        String saveResult = (String) formModel.getDataContainer().getValue("saveResult", null);
        if (saveResult == null) {
            ToastUtil.showToast(AppContext.getInstance(), "请先保存后在提交！");
            return;
        }
        JSONObject resultObject = null;
        try {
            resultObject = new JSONObject(saveResult);
            JSONObject dataObject = resultObject.getJSONObject("data");
            JSONObject flowTaskList = dataObject.getJSONObject("FLOW_TASK_LIST");

            int rowCount = flowTaskList.getInt("rowCount");
            if (rowCount == 0) {
                ToastUtil.showToast(AppContext.getInstance(), "数据异常，不能执行保存操作");
                return;
            }
            JSONObject efrowset = flowTaskList.getJSONArray("rowSetArray").getJSONObject(0).getJSONObject("dataMap");

            paramRoot.put("FLOW_NAME", efrowset.optString("FLOW_NAME"));
            paramRoot.put("TASK_NAME", efrowset.optString("TASK_NAME"));
            paramRoot.put("FLOW_ID", flowTaskList.optString("fLOW_ID"));
            paramRoot.put("NODE_ID", flowTaskList.optString("nODE_ID"));
            paramRoot.put("OBJ_GUID", efrowset.optString("OBJ_GUID"));
            paramRoot.put("MDL_ID", efrowset.optString("MDL_ID"));
            paramRoot.put("BIZ_MDL", efrowset.optString("MDL_ID"));
            paramRoot.put("BIZ_UNIT", flowTaskList.optString("bIZ_UNIT"));
            paramRoot.put("BIZ_DATE", flowTaskList.optString("bIZ_DATE"));
            paramRoot.put("BIZ_DJBH", flowTaskList.optString("bIZ_DJBH"));
            //意见
            paramRoot.put("OP_PROC_NOTE", opinion);
            paramRoot.put("OP_ID", flowTaskList.optString("oP_ID"));
            paramRoot.put("FLEX_PROCESS_FORM", efrowset.optString("FLEX_PROCESS_FORM"));
            paramRoot.put("TASK_UNIT", efrowset.optString("TASK_UNIT"));
            paramRoot.put("OP_LEVEL", opLevel);

            envRoot.put("LoginDate", DateUtil.getCurrentDate("yyyyMMdd"));
            envRoot.put("UserName", EnvironmentVariable.getProperty("UserName", ""));
            envRoot.put("IMUserId", EnvironmentVariable.getProperty(CHAT_USER_ID));
//            envRoot.put("Product", EnvironmentVariable.getProperty("Product"));
            envRoot.put("Product", Product);
            envRoot.put("UserCaption", EnvironmentVariable.getProperty("UserCaption", ""));

            param.put("envRoot", envRoot);
            param.put("paramRoot", paramRoot);
        } catch (Exception e) {
            e.printStackTrace();
            QMUIToastUtils.showQMUIToast(getTopActivity(), "提交失败,获取保存参数失败", QMUITipDialog.Builder.ICON_TYPE_FAIL);
            return;
        }

        String sRequestParam = "";
        try {
            JSONObject paramObject = new JSONObject();
            paramObject.put("Param", param.toString());

//            final HashMap<String, String> map1 = new HashMap<>();
//            map1.put("Param", param.toString());
            sRequestParam = URLEncoder.encode(paramObject.toString(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        HashMap<String, String> requestMap = new HashMap<>();
        requestMap.put("RequestParam", sRequestParam);

        String requestUrl = EnvironmentVariable.getProperty("OSPTaskURL", "") + "/OpenAPIService/SubmitTask";


        TCommonRequestManager.getInstance(AppContext.getInstance()).requestGetByAsyn(
                AppContext.getCurrentActivity().getClass().getSimpleName(),
                requestUrl, (HashMap<String, String>) requestMap, new TCommonRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String response) {
                        try {
                            JSONObject resultObject = new JSONObject(response);
                            if (resultObject.opt("errorCode").toString().equals("0")) {
                                QMUIToastUtils.showQMUIToast(getTopActivity(), "提交成功", QMUITipDialog.Builder.ICON_TYPE_SUCCESS);

                            } else {
                                new AlertDialog.Builder(ActivityUtils.getTopActivity()).
                                        setMessage(resultObject.opt("errorString").toString())
                                        .setTitle(R.string.common_text_hint).
                                        setPositiveButton(R.string.common_text_confirm,
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int i) {
                                                        dialogInterface.dismiss();
                                                    }
                                                }).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            QMUIToastUtils.showQMUIToast(getTopActivity(), "提交失败", QMUITipDialog.Builder.ICON_TYPE_FAIL);
                        }
                    }


                    @Override
                    public void onReqFailed(String errorMsg) {
                        QMUIToastUtils.showQMUIToast(getTopActivity(), "提交失败", QMUITipDialog.Builder.ICON_TYPE_FAIL);

                    }
                });
    }

    @Override
    public void doUpdate() {

    }

    @Override
    public String getID() {
        return null;
    }

    @Override
    public void setID(String id) {

    }

    @Override
    public void creationComplete() {

    }
}
